package com.itheima.service.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.List;
import java.util.Map;

//体检预约
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private JedisPool jedisPool;

    //通过ID查询预约相关信息（体检人姓名，预约日期，套餐名称，预约类型）
    @Override
    public Map findById(Integer id) throws Exception {
        Map map = orderDao.findById4Detail(id);
        //处理日期格式
        if (map!=null){
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate",DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    //体检预约
    @Override
    public Result order(Map map) throws Exception {

        //**********分布式锁，防止用户多次点击发送两次相同请求***********
        //缺点：redis分布式锁会占用redis的内存，需要定时清理
        Jedis resource = jedisPool.getResource();
        //如果没有key则设置值
        String orderDate = (String) map.get("orderDate");//预约日期
        String telephone = (String) map.get("telephone");//获取用户页面输入手机号
        String setmealId = (String) map.get("setmealId");//套餐ID

        String resourceSet = resource.getSet(orderDate + ":" + telephone + ":" + setmealId, "QAQ");
        resource.expire(orderDate+":"+telephone+":"+setmealId,600);//设置过期时间10分钟

        //测试使用，让线程睡眠10秒
        Thread.sleep(10000);

        if (StringUtils.isNotEmpty(resourceSet)){
            return new Result(false,"已预约该套餐辣，好好玩别瞎搞┑(￣Д ￣)┍");
        }
        //资源返回给jedispool
        resource.close();
        //**********分布式锁，防止用户多次点击发送两次相同请求***********


        //1.检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        //String orderDate = (String) map.get("orderDate");
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting==null){
            //指定日期没有进行预约设置，无法完成体检预约
            return new Result(false,MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        //2.检查用户所选择的日期是否已经预约满，如果预约满则无法预约
        //2.1获取可预约人数
        int number = orderSetting.getNumber();
        //2.2获取已预约人数
        int reservations = orderSetting.getReservations();
        if (reservations>=number){
            //已经预约满，无法预约
            return new Result(false,MessageConstant.ORDER_FULL);
        }

        //3.检查用户是否重复预约（同一个用户名在同一天预约了同一个套餐），如果重复预约则无法完成再次预约
        //String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        if (member!=null){
            //判断是否重复预约
            //3.1获取会员ID
            Integer memberId = member.getId();
            //3.2获取预约日期
            Date order_Date = DateUtils.parseString2Date(orderDate);
            //3.3获取套餐ID
            //String setmealId = (String) map.get("setmealId");
            Order order = new Order(memberId, order_Date, Integer.parseInt(setmealId));
            //3.4根据条件查询
            List<Order> list = orderDao.findByCondition(order);
            if (list!=null && list.size()>0){
                //说明存在重复预约，无法再次完成预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }else {
            //4.检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String)map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String)map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            //自动完成会员注册
            memberDao.add(member);
        }
        //5.预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());  //设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));  //设置预约日期
        order.setOrderType((String) map.get("orderType"));  //设置预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO); //设置到诊状态
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));    //套餐ID
        orderDao.add(order);

        orderSetting.setReservations(orderSetting.getReservations()+1); //设置已预约人数
        orderSettingDao.editReservationsByOrderDate(orderSetting);

        //预约成功并返回预约ID
        return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
    }
}
